package org.ting.j20250110_gobang.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ting.j20250110_gobang.mapper.UserMapper;
import org.ting.j20250110_gobang.model.User;
import org.ting.j20250110_gobang.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @RequestMapping("/login")
    public User login(String username, String password, HttpServletRequest request) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            //用户名或密码为空,返回空用户信息
            return new User();
        }
        User user = userService.login(username, password);

        //把登录用户信息储存在session中，方便后续获取，或验证登录状态
        HttpSession session = request.getSession(true);//参数true表示回话不存在时允许创建新会话
        session.setAttribute("user", user);
        return user;
    }

    @RequestMapping("/register")
    public User register(String username, String password,  HttpServletRequest request) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            //用户名或密码为空,返回空用户信息
            return new User();
        }
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setScore(500);
            userService.register(user);
            return user;
        }catch (DuplicateKeyException e) {
            //用户名存在，引发异常，返回空对象
            return new User();
        }
    }

    @RequestMapping("/getLoginUser")
    public User getLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);//回话不存在时不允许创建会话
        try{
            User user = (User)session.getAttribute("user");
            //返回数据库中最新的用户数据
            return userMapper.getUserByName(user.getUsername());
        }catch(NullPointerException e) {
            //session为null返回空对象
            return new User();
        }

    }
}
